package com.hg.controller;

import com.alibaba.druid.sql.visitor.functions.If;
import com.hg.util.IDUtils;
import com.hg.util.QiniuUtils;
import com.hg.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/file")
public class UploadFileController {
    private List<String> contentTypeList = Arrays.asList("image/jpeg", "image/gif", "image/png");


    @RequestMapping("/upload")
    public Result uploadFile(MultipartFile file) {
        try {
            // 校验文件的类型
            String contentType = file.getContentType();
            if (!contentTypeList.contains(contentType)){
                return Result.error("文件类型不合法");
            }
            // 校验文件的内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                return Result.error("文件内容不合法");
            }
            // 保存到服务器
            String originalFilename = file.getOriginalFilename();
            String beginName = IDUtils.genImageName();
            String imageName = beginName + originalFilename.substring(originalFilename.lastIndexOf("."));
            QiniuUtils.upload2Qiniu(file.getBytes(), imageName);
            //返回图片的地址

            return Result.ok("http://sza21a6o2.hb-bkt.clouddn.com/"+imageName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }
}
